package com.example.config.interceptor;
import com.example.common.Constants;
import com.example.exception.ServiceException;
import com.example.service.IUserService;
import com.example.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 设置拦截器拦截token
* */
public class JwtIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //让OPTIONS请求通过
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

        response.setContentType("text/html;charset=utf-8");
        // 获取请求sout头中的token
        String token = request.getHeader("token");

        try {
            TokenUtils.checkToken(token);
        } catch (Exception ex) {
            throw new ServiceException(Constants.CODE_500,"令牌过期，请重新登录");
        }
        return true;
    }
}
